<template>
  <div class="videos">
    <div class="returngo" @click="runturgo"><icon-undo /> 返回</div>
    <div class="videos-look">
      <video ref="videoEl" controls :poster="poster" width="100%" class="videos-height"></video>
      <div style="margin: 1vw 0">{{ contentList.datalist.CName }}</div>
      <div class="brief-introduction">
        <div class="container">
          <div class="img">
            <img class="imgspan" src="/img/img-span.png" alt="" />
          </div>
          <span>{{ videoType == 7 ? '关联试题' : '关联学案' }}</span>
        </div>
        <div class="Loading" v-if="!contentList.datalist.Content">
          <!-- <a-spin dot /> -->
        </div>
        <p class="videos-text" v-if="videoType != 7" v-html="contentList.datalist.Content"></p>
        <div class="answerq" v-if="videoType == 7">
          <div class="topic">
            <div class="timi" v-for="(item, index) in contentList.datalist" :key="index">
              <!-- <span>{{ item.number }}.</span> -->
              <span class="timi-p">{{ (index+1) }}.</span>
              <span class="timi-p" v-html="item.test"></span>
              <span v-if="
                item.if_choose != 1 && item.if_choose != 2 && item.if_choose != 3
              " style="color: #fb6d30">本题暂不支持在线作答，请在纸上写上正确答案</span>
              <div class="timi-listtaxt" v-for="(itemlist, subIndex) in item.sub" :key="subIndex">
                {{ itemlist.id }}. <span v-html="itemlist.sub_title"></span>
                <span v-if="
                  itemlist.if_choose != 1 &&
                  itemlist.if_choose != 2 &&
                  itemlist.if_choose != 3
                " style="color: #fb6d30">本题暂不支持在线作答，请在纸上写上正确答案</span>
                <div class="time-cleck" v-for="(itemsdata, optionIndex) in itemlist.sub_options" :key="optionIndex"
                  @click="
                    type != 2
                      ? toggleOption(index, subIndex, optionIndex, 'sub')
                      : null
                    ">
                  <a-row class="grid-demo">
                    <a-col :span="22">
                      <div class="col-name" v-html="itemsdata"></div>
                    </a-col>
                    <a-col :span="2">
                      <div class="col-name-right">
                        <icon-check size="25" v-if="isSelected(index, subIndex, optionIndex, 'sub')" />
                        <!-- <icon-close /> -->
                      </div>
                    </a-col>
                  </a-row>
                  <!-- </a-space> -->
                </div>
                <div class="answer" v-if="itemlist.sub_analytic">
                  <div style="margin-top: 24px">
                    <div>
                      <b style="color: #0075ff">解析 </b>&nbsp;
                      <span v-html="itemlist.sub_analytic"></span>
                    </div>
                    <p class="answer-text-p"></p>
                  </div>
                </div>
              </div>
              <div class="time-cleck" v-for="(items, indexs) in item.test_options" :key="indexs"
                @click="type != 2 ? toggleOption(index, null, indexs, 'main') : null">
                <a-row class="grid-demo">
                  <a-col :span="22">
                    <div class="col-name" v-html="items"></div>
                  </a-col>

                  <a-col :span="2">
                    <div class="col-name-right">
                      <icon-check size="22" v-if="isSelected(index, null, indexs, 'main')" />
                      <!-- <icon-close /> -->
                    </div>
                  </a-col>
                </a-row>
                <!-- </a-space> -->
              </div>
            </div>
            <div style="margin-top: 20px;">
              <a-button class="buttom" type="outline" @click="checkAnswerBtn">查看答案</a-button>
            </div>
            <div style="margin-top:20px" v-if="checkAnswer">
              <div class="answerwrap" style="display: inline-block;margin-bottom: 10px;" v-for="(item,indexs) in contentList.datalist" :key="indexs">
                <span>{{ indexs+1 }}.</span>
                <span v-html="item.analytic"></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="videos-right" ref="videosRightRef">
      <div class="videos-name">
        <div class="videos-top">课程列表</div>
      </div>

      <div class="videos-list">

        <div class="videos-listname" v-for="(item, index) in contentListdata" :key="index"
          @click="videoscick(item, index)">
          <div :class="{ 'active-title': currentActiveIndex === index }">
            {{ item.VideoName }}
          </div>
          <div>
            <img class="bofang" :class="{ show: currentActiveIndex === index }" src="/img/bofang.png" alt="" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, watch, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  catsaveRecordDetail,
  catstudyCourse,
  catsaveVodeoFinished,
  catgetVideoLimit,
} from "@/api/study";
import Hls from "hls.js";
import useUserStore from "@/store/modules/user";

const route = useRoute();
const router = useRouter();

const checkAnswer = ref(false);
// 滚动
const videosRightRef = ref<HTMLElement | null>(null);
const isLoading = ref(false);
const hasMore = ref(true);
const userStore = useUserStore();
const currentActiveIndex = ref(0);
const receivedData = route.query.VID;
// 检查浏览器是否支持 hls.js
const videoEl = ref<HTMLVideoElement | null>(null);
const hlsInstance = ref<Hls | null>(null);
const poster = ref(""); // 视频封面URL
const videoUrl = ref(""); // M3U8视频URL
const VideoTime = ref();
// 新增播放时长相关状态
const playDuration = ref(0); // 已播放时长(秒)
const maxPlayedDuration = ref(0); // 最大播放进度(秒)
const intervalId = ref<NodeJS.Timeout | null>(null); // 定时器ID

const videoType = route.query.type;
console.log("videoType",videoType)
const formsaveRecord = reactive({
  kid: 0, // 知识点
  mid: 0, //
  rid: 0, //
  times: 1,
  cTime: 0,
});
const subjectID = userStore.$state.subjectID;
const formVodeoFinished = reactive({
  kid: 0, //知识点
  gid: 0, //年级
  sid: 0, //学科
  vid: 0,
});
// 1. 添加一个ref来存储上次播放时间
const lastPlayedTime = ref(0);
const isVideoFinished = ref(false); // 添加标志位
const VideoTimedata = ref();

const checkAnswerBtn = () => { 
  checkAnswer.value = true;
};

// 新增：处理拖动进度条事件
const handleSeeking = () => {

  isVideoFinished.value = false;
  // 如果定时器不存在，重新开启
  if (!intervalId.value) {
    startTracking();
  }
};

// 初始化HLS播放器
const initHlsPlayer = async () => {
  if (!videoEl.value) return;

  // 先移除旧的事件监听
  videoEl.value.removeEventListener("timeupdate", handleTimeUpdate);
  videoEl.value.removeEventListener("seeking", handleSeeking);

  // 添加新的事件监听
  videoEl.value.addEventListener("timeupdate", handleTimeUpdate);
  videoEl.value.addEventListener("seeking", handleSeeking);

  try {
    if (Hls.isSupported()) {
      hlsInstance.value = new Hls();
      hlsInstance.value.loadSource(videoUrl.value);
      hlsInstance.value.attachMedia(videoEl.value);
      hlsInstance.value.on(Hls.Events.MANIFEST_PARSED, () => {
        // 添加时间跳转
        if (lastPlayedTime.value > 0) {
          videoEl.value!.currentTime = lastPlayedTime.value;
        }
        videoEl.value?.play().catch((e) => {
        });
      });

      hlsInstance.value.on(Hls.Events.ERROR, (event, data) => {
        if (data.fatal) {
          switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
              hlsInstance.value?.startLoad();
              break;
            case Hls.ErrorTypes.MEDIA_ERROR:
              hlsInstance.value?.recoverMediaError();
              break;
            default:
              destroyHlsPlayer();
              break;
          }
        }
      });
    } else if (videoEl.value.canPlayType("application/vnd.apple.mpegurl")) {
      // 原生支持HLS的浏览器（如Safari）
      videoEl.value.src = videoUrl.value;
      videoEl.value.addEventListener("loadedmetadata", () => {
        // 添加时间跳转
        if (lastPlayedTime.value > 0) {
          videoEl.value!.currentTime = lastPlayedTime.value;
        }
        videoEl.value?.play().catch((e) => {
        });
      });
    }
  } catch (error) {
  }
};

// 处理时间更新
const handleTimeUpdate = () => {
  if (!videoEl.value) return;
  // 更新当前播放时间
  playDuration.value = Math.floor(videoEl.value.currentTime);

  // 记录最大播放进度
  if (videoEl.value.currentTime > maxPlayedDuration.value) {
    maxPlayedDuration.value = Math.floor(videoEl.value.currentTime);
  }

  // 检查是否播放完成（增加1秒容差）
  if (Math.abs(videoEl.value.currentTime - VideoTime.value) <= 1 && !isVideoFinished.value) {
    // 播放完
    isVideoFinished.value = true; // 设置标志位为已完成
    const permission = JSON.parse(localStorage.getItem("permission") as any);
    formVodeoFinished.gid = permission.GradeID;
    formVodeoFinished.sid = Number(subjectID);
    formVodeoFinished.vid = Number(receivedData);

    catsaveVodeoFinished(formVodeoFinished).then((res: any) => {
      // 1. 清除定时器

      savePlayProgress(Number(VideoTimedata.value));
      if (intervalId.value) {
        clearInterval(intervalId.value);
        intervalId.value = null;

      }
    });
  }
};

// 开始记录播放时长
const startTracking = () => {
  // 如果已有定时器，先清除
  if (intervalId.value) {
    clearInterval(intervalId.value);
  }

  // 每30秒记录一次到服务器
  intervalId.value = setInterval(() => {
    if (maxPlayedDuration.value > 0 && !isVideoFinished.value) {

      savePlayProgress(Number(playDuration.value));
    }
  }, 30000);
};

// 保存播放进度到服务器
const savePlayProgress = async (duration: number) => {
  try {
    formsaveRecord.cTime = duration;
    formsaveRecord.rid = Number(receivedData);
    await catsaveRecordDetail(formsaveRecord).then((res: any) => {

    });
  } catch (error) {
  }
};

// 销毁HLS实例
const destroyHlsPlayer = () => {
  if (hlsInstance.value) {
    hlsInstance.value.destroy();
    hlsInstance.value = null;
  }

  // 1. 清除定时器
  if (intervalId.value) {
    clearInterval(intervalId.value);
    intervalId.value = null;
  }
  // 2. 移除video元素的事件监听
  if (videoEl.value) {
    videoEl.value.removeEventListener("timeupdate", handleTimeUpdate);
    videoEl.value.removeEventListener("seeking", handleSeeking);
    // 重置video元素
    videoEl.value.pause();
    videoEl.value.removeAttribute("src");
    videoEl.value.load();
  }
};

const from = reactive({
  page: "1",
  limit: "10",
  vid: "",
});

const videoscick = (item: any, e: any) => {
  currentActiveIndex.value = e;
  from.vid = item.VID;
  video();
};

const videoList = ref();
const contentList = reactive({
  datalist: {
    CName: '',
    Content: ''
  },
});

const contentListdata = ref([]);


const video = () => {
  if (route.query.id == "1") {
    from.vid = receivedData;
  }

  catstudyCourse(from).then((res: any) => {
    videoList.value = res.videoList;
    if (res.contentList[0]) {
      if(videoType == 7){
        contentList.datalist = res.contentList[0].Test;
      }else{
        contentList.datalist.Content = res.contentList[0].Content;
      }
      
    }

    if (route.query.id == "1") {
      contentListdata.value = []
      contentListdata.value.push(res.videoList);
    }
    //
    videoUrl.value = videoList.value.ListPath;
    poster.value = videoList.value.CoverPath;
    VideoTime.value = videoList.value.VideoTime - 1;
    VideoTimedata.value = videoList.value.VideoTime;
    lastPlayedTime.value = videoList.value.currenttime; //上次的时间

    if (videoUrl.value) {
      initHlsPlayer().then(() => {
        startTracking(); // 初始化后开始跟踪
      });
    }
  });
};

const videoname = reactive({
  cid: 0, //vid
  page: 1, //分页
  limit: 30, //条数
});
const VideoLimit = ref();

const pageNumChangelist = (page: number) => {
  if (page !== 0) {
    videoname.page = page;
    // VideoLim("2");
  }
};

const totalPageNum = ref();

const VideoLim = (e: any) => {
  catgetVideoLimit(videoname).then((res: any) => {
    if (contentListdata.value.length > 0) {
      contentListdata.value.push(...res.list);
    } else {
      contentListdata.value = res.list;
    }

    totalPageNum.value = res.totalPageNum;
    from.vid = res.list[0].VID;
    if (e == "1") {
      video();
    }
  });
};

// 滚动
// 新增防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: number;
  return (...args: any[]) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
};

// 修改后的handleScroll
const handleScroll = debounce(() => {
  if (!videosRightRef.value || isLoading.value || !hasMore.value) return;

  const { scrollTop, scrollHeight, clientHeight } = videosRightRef.value;
  const distanceFromBottom = 50; // 触发加载的距离阈值

  // 判断是否滚动到底部
  if (scrollTop + clientHeight >= scrollHeight - distanceFromBottom) {
    loadMoreData();
  }
}, 200);

// 修改后的loadMoreData
const loadMoreData = async () => {
  if (videoname.page > Number(totalPageNum.value)) {
    hasMore.value = false;
    return;
  }

  isLoading.value = true;
  try {
    videoname.page++;
    await VideoLim("2");
  } catch (error) {
    videoname.page--; // 失败时回退页码
  } finally {
    isLoading.value = false;
  }
};
watch(
  () => userStore.$state.subjectID,
  async (newValue, oldValue) => {
    try {
      if (oldValue) {
        router.back();
        // router
      }

      // docsaveData.value = data;
    } catch (error) {
    }
  },
  { immediate: true }
);
onMounted(() => {
  if (videosRightRef.value) {
    videosRightRef.value.addEventListener("scroll", handleScroll);
  }

  if (route.query.kid) {
    formsaveRecord.kid = Number(route.query.kid);
    formVodeoFinished.kid = Number(route.query.kid);
  }
  if (route.query.id == "1") {
    // videoscick('',0);
    video();
  } else {
    videoname.cid = Number(receivedData);
    VideoLim("1");
  }
});
const runturgo = () => {
  // router.back();
  router.push({
    path: "/Study",
    query: { Vkid: route.query.kid, page: route.query.page, type: route.query.type, keyword: route.query.keyword }
  });
};
onBeforeUnmount(() => {
  destroyHlsPlayer();
  // 最终保存一次进度
  if (maxPlayedDuration.value > 0) {
    if (!isVideoFinished.value) {
      savePlayProgress(Number(playDuration.value));
    }
  }
  if (videosRightRef.value) {
    videosRightRef.value.removeEventListener("scroll", handleScroll);
  }
});
</script>
<style lang="less" scoped>
.videos {
  margin: 1vw;
  display: flex;
  flex-wrap: wrap;
  background: #f7fbff;
  position: relative;
  margin-top: 50px;
}

.returngo {
  position: absolute;
  cursor: pointer;
  left: 0;
  top: -70px;
}

.videos-look {
  margin-right: 1vw;
  padding-right: 1vw;
  width: 48vw;
  background-color: #fff;
}

.videos-right {
  height: 90vh;
  overflow: auto;
  background-color: #fff;
  flex: 1;
}

.videos-height {
  height: 50vh;
}

.brief-introduction {
  //     width: 1096px;
  // height: 215px;
  //   margin: 1vw;
  background: #f7fbff;
  border-radius: 12px;
  padding: 1vw;
}

.imgspan {
  height: 1vw;
  margin-right: 0.5vw;
}

// .img
.bofang {
  width: 1vw;
  // height: 2vh;
  display: none;
}

.bofang.show {
  display: block;
}

.active-title {
  color: #0075ff;
  //   font-size: 1vw;
  font-weight: bold;
}

.container {
  display: flex;
  align-items: center;
}

.videos-text {
  margin-top: 1vw;
}

.videos-name {
  margin: 1vw;
  padding: 1vw 0;
  border-bottom: 1px solid #ededed;
}

.videos-list {
  margin: 1vw;
  // padding: 1vw 0;
  // height: 70vh;
}

.videos-listname {
  // padding: vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  // margin-top: 10px;
  // height: 70vh;
  margin-top: 1vw;
  cursor: pointer;
}

.videos-top {
  //     width: 144px;
  // height: 25px;
  // font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 18px;
  color: #03305c;
  // line-height: 25px;
  text-align: left;
  font-style: normal;
}

@media (max-width: 768px) {
  .imgspan {
    height: 4vw;
    margin-right: 2vw;
  }

  .videos-look {
    margin-right: 1vw;
    padding-right: 1vw;
    width: 100%;
    background-color: #fff;
  }

  .returngo {
    position: absolute;
    cursor: pointer;
    left: 0;
    top: -55px;
  }

  .videos-right {
    width: 100vw;
    background-color: #fff;
    //   padding: 1vw;
    //   background-color: green;
  }

  .bofang {
    width: 3vw;
    // height: 2vh;
    display: none;
  }
}
.timi {
  margin-top: 24px;
  padding: 0vw 1vw 1vw;
  // height: 100%;
  overflow: auto;
  /* WebKit 浏览器（Chrome、Safari） */
  scrollbar-width: none;
  -ms-overflow-style: none;
  background-color: #fff;
  // height: 75vh;
  .timi-p {
    font-family: DINAlternate, DINAlternate;
    font-weight: 500;
    font-size: 1.1vw;
    color: #03305c;
    margin-top: 1vw;
    line-height: 32px;
    text-align: left;
    font-style: normal;
  }
  .timi-listtaxt {
    margin: 1vw 0;
    color: #03305c;
    font-size: 1.1vw;
  }
}
.answerwrap{
  padding: 0px 10px;
  line-height: 30px;
  span{
    float: left;
  }
  p{
    display: inline-block;
  }
}
</style>
